package com.tc.itfarm.web.action;

import com.tc.itfarm.api.common.JsonMessage;
import com.tc.itfarm.api.util.EncoderUtil;
import com.tc.itfarm.model.User;
import com.tc.itfarm.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangdongdong on 2016/8/30.
 */
@Controller
@RequestMapping("/login")
public class LoginAction {

    @Resource
    private UserService userService;

    @RequestMapping("toLogin")
    public String toLogin(HttpServletRequest request) {
        return "login/login";
    }

    @RequestMapping("/loginDo")
    @ResponseBody
    public JsonMessage loginDo(User user, HttpServletRequest request) {
        User u = userService.select(user.getUsername(), EncoderUtil.md5(user.getPassword()));
        JsonMessage jm = new JsonMessage();
        if (u != null) {
            jm.setResultMessage("登陆成功!");
            jm.setSuccess(true);
            jm.setResult(u);
            request.getSession().setAttribute("user", u);
        } else {
            jm.setResultMessage("用户名或密码错误!");
            jm.setSuccess(false);
        }
        return jm;
    }

    @RequestMapping("loginOut")
    @ResponseBody
    public JsonMessage loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        JsonMessage jm = new JsonMessage();
        jm.setResultMessage("注销成功!");
        jm.setSuccess(true);
        return jm;
    }
}
